/**
 * @fileoverview Share Tools view.
 * @author Jonathan Hensley <jhensley@gannett.com>
 */
define([
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'views/modules/scroller/vertical-scroll',
    'facebook'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App,
    VerticalScroll,
    Facebook
) {


    /**
     * View class.
     */
    var CommentView = Backbone.View.extend({

        /**
         * Initialize view.
         */
        initialize: function() {
            _.bindAll(this, 'toggle');
            this.subviews = {};
            this.pubSub = {
                'breakingbar:after:open': this.scalePanel
            };
            PubSub.attach(this.pubSub, this);
            this.toggle(this.options.event);
        },

        /**
         * Listen for new comment to update count.
         */
        attachCommentListener: function() {

            Facebook.getFB(_.bind(function(FB) {
                    
                FB.Event.subscribe('comment.create',
                    _.bind(function() {
                        PubSub.trigger('comment:created');
                    }, this)
                );

                FB.Event.subscribe('comment.remove',
                    _.bind(function() {
                        PubSub.trigger('comment:removed');
                    }, this)
                );

            }, this));

        },

        /**
         * Stop listening for new comments.
         */
        unattachCommentListener: function() {
            Facebook.getFB(function(FB) {
                FB.Event.unsubscribe('comment.create');
                FB.Event.unsubscribe('comment.remove');
            });
        },

        /**
         * Load Facebook Comments social plugin.
         */
        loadComments: function() {
            Facebook.getFB(_.bind(function(FB) {
                FB.XFBML.parse(this.$scrollable[0]);
                this.scrollableHeight = this.$scrollable.height();
                this.heightPoll = setInterval(_.bind(function(){
                    if (this.scrollableHeight !== this.$scrollable.height()) {
                        this.scrollableHeight = this.$scrollable.height();
                        this.scalePanel();
                    }
                }, this), 200);

                // We need to use native scrolling for FF/IE/iOS because the iframes capture the
                // mousewheel/touch events so we can't actually scroll properly
                var nativeScrolling = false;
                if (!$.browser.webkit) {
                    nativeScrolling = true;
                } else if (Modernizr.touch) {
                    this.$scrollWrap.css({'-webkit-overflow-scrolling': 'touch'});
                    if (this.$scrollWrap.css('-webkit-overflow-scrolling') === 'touch') {
                        nativeScrolling = true;
                    }
                }
                if (nativeScrolling) {
                    this.$scrollWrap.css('overflow', 'auto');
                } else {
                    // Initialize the Vertical Scroll
                    this.subviews.vscroll = new VerticalScroll({
                        el: this.$scrollWrap,
                        draggerPaddingTop: 0,
                        color: 'lighter'
                    });
                }
            }, this));
        },

        /**
         * Sets up the proper height of the panel.
         */
        scalePanel: function() {
            // if (!scrollableHeight) scrollableHeight = this.scrollableHeight;
            // var availHeight = this.$win.height() ;
            // var height = scrollableHeight > availHeight ? availHeight - 20 : scrollableHeight;
            this.$scrollWrap.css('height', this.$win.height() - App.get('headerEl').height() - 115);

            //gradient overlay only shows up if the scrollbar also shows up 
            if ( this.$('.vertical-scroll').css('display') === 'none' ){
                this.$gradient.hide()
            } else{   
                this.$gradient.css('display', 'block'); 
                this.$gradient.css('bottom', 15);
            }
            if (this.subviews.vscroll) this.subviews.vscroll.refresh();
        },

        /**
         * Toggle the share panel open/closed.
         * @param {Event} e Browser event.
         * @param {boolean=} close Force close.
         */
        toggle: function(e, close) {
            this.$btn = this.$('.btn');
            this.$scrollWrap = this.$('.util-bar-scroll-wrap');
            close = close || this.$btn.hasClass('open');
            if (e) {
                if ($(e.target).closest(this.$scrollWrap).length) return;
            }
            if (close) {
                this.$btn.removeClass('open');
                this.$flyout.removeClass('open');
                clearInterval(this.heightPoll);
                PubSub.trigger('uotrack', 'UtilityBarFacebookClose');
                this.destroy();
            } else if (close === false) {                
                this.$body = App.get('body');

                // Avoid triggering the body click being added below. But simulate
                // a click to avoid unwanted stopped propagation for other open
                // flyouts.
                this.$body.trigger('click');
                if (e) e.stopPropagation();
                this.$flyout = this.$('.flyout-comments');
                this.$scrollable = this.$('.scrollable-content');
                this.$fbPluginWrap = this.$('.fb-plugin-wrap');
                this.$gradient = this.$('.util-bar-gradient-overlay');
                // this.$('.fb-comments').attr('data-href', App.getPageUrl());
                this.$utilWrap = this.$el.closest('.utility-wrap');
                this.$header = $('#header');
                this.$win = App.get('win');
                this.$btn.addClass('open');
                this.$flyout.addClass('open');
                this.loadComments();
                this.attachCommentListener();
                PubSub.trigger('uotrack', 'UtilityBarFacebookOpen');
                this.$body.on('click.' + this.cid, this.toggle);
            }
        },

        /**
         * Clean up view.
         * Removes event handlers and element (optionally).
         * @param {boolean} removeEl option to also remove View from DOM.
         */
        destroy: function(removeEl) {
            clearInterval(this.heightPoll);
            this.$body.off('click.' + this.cid);
            this.unattachCommentListener();
            this.undelegateEvents();
            _.each(this.subviews, function(view){
                if (typeof view.destroy !== 'undefined') {
                    view.destroy(removeEl);
                }
            });
            if (this.pubSub){
                PubSub.unattach(this.pubSub, this);
            }
            if (removeEl) {this.remove();}
        }
    });

    /**
     * Return view class.
     */
    return CommentView;
});
